﻿#include "MyGrib.h"
#include "OCVolume/VolumeJsonWriter.h"
#include "rapidjson/writer.h"
#include "rapidjson/stringbuffer.h"

template<> MyGrib* CSingleton<MyGrib>::msSingleton = 0;

String MyGrib::openGrib(String body)
{
	Json::Value value;
	Json::Reader reader;
	reader.parse(body, value);
	String fileName = value["fileName"].asCString();

	_gribReader.reset(new GribReader());
	if (!_gribReader->open(U2A(fileName), true))
	{
		_gribReader = nullptr;
	}

	return _gribReader == nullptr ? "false" : "true";
}

String MyGrib::listGribVar()
{
	if (_gribReader == nullptr) return "";
	Json::Value value1 = _gribReader->getVars();
	return ServerUtil::jsonToString(value1);
}

class MyGribWriter : public VolumeJsonWriter
{
public:
	MyGribWriter() {
	}

	String _result;

	std::unique_ptr<std::ostream> _stream;

	virtual std::unique_ptr<std::ostream> getOutStream(const VolumeGridData& ncGridData, const VolumeOptions& ncOptions)
	{
		return std::make_unique<StringStream>();
	}

	virtual void onWriteDone(std::ostream& ostream)
	{
		_result = ((StringStream*)(&ostream))->str();
	}
};


String MyGrib::getGribVar(String name,String timeIndex1, String levelIndex1)
{
	if (_gribReader == nullptr) return "";
	StringMap globalOptions;
	VolumeOptions options(globalOptions);

	options.setWriter(new MyGribWriter());

	int levelIndex = StringConverter::parseInt(levelIndex1,0);
	int timeIndex = StringConverter::parseInt(timeIndex1, 0);

	_gribReader->extract(U2A(name), options, levelIndex, timeIndex);

	return ((MyGribWriter*)(&options.getWriter()))->_result;
}

